package graduation.dao.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import graduation.dao.ApplyDao;
import graduation.entity.Apply;
import graduation.entity.User;

@Repository
public class ApplyDaoImpl extends HibernateDaoSupport implements ApplyDao{
	@Autowired  
    public void setSessionFactoryOverride(SessionFactory sessionFactory)  
    {  
        super.setSessionFactory(sessionFactory);  
    }
	
	@Resource
	private SessionFactory sessionFactory;

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	

	/**
	 * 添加申请
	 */
	@Override
	public void addApply(Apply apply) {
		// TODO Auto-generated method stub
		Session session = this.getSession();
		session.save(apply);
	}
	/**
	 * 通过id查询
	 */
	@Override
	public Apply findById(Integer id) {
		// TODO Auto-generated method stub
		Session session = this.getSession();
		String hql = "from Apply where id = ?";
		return (Apply) session.createQuery(hql).setParameter(0, id).uniqueResult();
	}

	/**
	 * 修改
	 */
	@Override
	public void update(Apply apply) {
		// TODO Auto-generated method stub
		Session session = this.getSession();
		session.update(apply);
	}

	/**
	 * 通过我的邮箱查询
	 */
	@Override
	public List<Apply> findBySender(String sender) {
		// TODO Auto-generated method stub
		Session session = this.getSession();
		String hql = "from Apply a where a.sender=?";
		
		return session.createQuery(hql).setParameter(0, sender).list();
	}

	/**
	 * 通过收件人的邮箱修改
	 */
	@Override
	public List<Apply> findByReceiver(String receiver) {
		// TODO Auto-generated method stub
		Session session = this.getSession();
		String hql = "from Apply a where a.receiver=?";
		return session.createQuery(hql).setParameter(0, receiver).list();
	}

	/**
	 * 通过我的邮箱和批复状态获取所有申请
	 */
	@Override
	public List<Apply> getMyApplyByStatus(String sender, Boolean dealStatus) {
		// TODO Auto-generated method stub
		Session session = this.getSession();
		String hql = "from Apply a where a.sender=? and a.dealStatus=?";
		return session.createQuery(hql).setParameter(0, sender).setParameter(1, dealStatus).list();
	}


	@Override
	public List findByUserId(String userId) {
		// TODO Auto-generated method stub
		String hql = "from Apply a where a.userId=?";
		Query query = this.getSession().createQuery(hql);
		query.setParameter(0, userId);
		return query.list();
	}


	@Override
	public void delApplyById(int id) {
		// TODO Auto-generated method stub
		String hql = "delete Apply A where A.id = ?";
		Query query = this.getSession().createQuery(hql);
		query.setParameter(0, id);
		query.executeUpdate();
	}
	

}
